package com.mybatisplus.filters;

import com.mybatisplus.utils.ToHttpServletUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/***@author: 郭政荣
 *@Date: 2023/5/18 22:22
 **/
@CrossOrigin(value = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE})
@WebFilter(filterName = "RobFilter", urlPatterns = "/studentRob/*")
public class RobFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException, NullPointerException {
//        抢答过滤器
        HttpSession session = ToHttpServletUtil.toHttpServletRequest(request).getSession(false);
        //使用自定义类封装的toHttpServletXXX(XXX)方法穿入的转化成http对应的request对象和response对象
        if (session != null) {
            System.out.println("用户已登录,放行用户");
            chain.doFilter(request, response);
        } else {
            HttpServletResponse httpServletResponse = ToHttpServletUtil.toHttpServletResponse(response);
            System.out.println("用户未登录，拦截，发送重定向");
            httpServletResponse.setHeader("REDIRECT", "REDIRECT");
            httpServletResponse.setHeader("CONTENTPATH", "/");
        }
    }
}
